const Seneca = require('seneca');
const seneca = Seneca().use('seneca-as-promised');
const cp = require('child_process');
const co = require("co");
const sleep = require("ko-sleep");

function exec(cmd) {
    return new Promise((resolve, reject) => {
        cp.exec(cmd, function(e, stdout, stderr) {
            if (e) {
                reject(e);
            }
            resolve({
                stderr: stderr,
                stdout: stdout
            });
        });
    });
}
let isStarted = false;
module.exports = {
    startServer: co.wrap(function*() {
        if (!isStarted) {
            let res = yield exec('/nodejs/bin/pm2 start /app/seneca_lock.js -i 1');
            console.log(res.stdout);
            console.log(res.stderr);
            yield sleep(1000);
            isStarted = true;
        }
    }),
    getClient: function() {
        return seneca.client({
            type: "tcp",
            port: 8261,
            pin: {
                role: "lock"
            }
        });
    }
};
